package com.zte.claa.inficombo.csa.app.service.devpower.impl;


import java.util.List;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zte.claa.inficombo.csa.app.dao.mysql.impl.DevPowerBaseMapper;
import com.zte.claa.inficombo.csa.app.model.devpower.DevPowerBase;
import com.zte.claa.inficombo.csa.app.service.devpower.DevPowerBaseService;
import com.zte.claa.inficombo.csa.app.service.devpower.DevPowerConverter;




@Service
public class DevPowerBaseServiceImpl implements DevPowerBaseService {
	
	private static final Logger logger = LoggerFactory.getLogger(DevPowerBaseServiceImpl.class);

	private static final String UL = "ul";//高限
	private static final String DL = "dl";//低限
	private static final String GEAR = "gear";//档位间隔:eg 5---->每次变化5个单位,如20%,25%,30%	
	//默认电量计算公式参数
	private static final String DEFAUL_JSONPARA = "{\"ul\":4.2,\"dl\":3.4,\"gear\":10}";

	
	@Autowired
	private DevPowerBaseMapper mapper;


	@Override
	public List<DevPowerBase> queryByDev(String deveui) throws Exception{
		List<DevPowerBase> list = mapper.queryByDev(deveui);		
		this.setConverter(list);		
		return list;
	}
	
	
	//根据参数生成电量计算转换器
	private void setConverter(List<DevPowerBase> list)throws Exception{
		if(list == null || list.size() == 0)
			return;
		JSONObject jsonObject = null;
		float ul = 0;
		float dl = 0;
		int gear = 0;
		for(DevPowerBase devPowerBase : list){
			jsonObject = splitFunctionJsonPara(devPowerBase.getJsonpara());		
			if(jsonObject == null){
				jsonObject = new JSONObject(DEFAUL_JSONPARA);	
			}
			
			try{
				ul = (float)jsonObject.getDouble(UL);
				dl = (float)jsonObject.getDouble(DL);
				gear = (int)jsonObject.get(GEAR);
				DevPowerConverter converter = new DevPowerConverter(ul,dl,gear,devPowerBase.getFullpowercap());
				devPowerBase.setConverter(converter);
			}catch (Exception e) {	
				logger.error("setConverter error: " + e.getMessage());
				continue;
			}							
		}		
	} 
	

	
	//解析辅助计算参数
	private JSONObject splitFunctionJsonPara(String jsonStr){
		logger.info("Function json paramter str: " + jsonStr);		
		if(jsonStr == null || jsonStr.length() == 0){
			return null;
		}					
		try{			
			return new JSONObject(jsonStr);				
		}catch(Exception e){	
			logger.error("splitFunctionJsonPara error: ", e.getMessage());
			return null;
		}		
	}
		
}
